//app.js
var promise = require('utils/request.js');
const unionId = wx.getStorageSync('unionId')
App({
  onLaunch: function() {
    let that=this
    if (unionId){
      that.getIdentity(unionId)
    }else{
      that.wxLogin() 
    }
  },
  wxLogin: function() {
    let that = this
    // 微信登陆获取code
    wx.login({
      success: res => {
        console.log(res)
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        promise.notAuthorizeRequest('miniapp/jscode2Session/' + res.code, 'Get', '', null, 4, {
          success: function(data) {
            if (data) {
              // promise.tLogin(data.unionid)
              wx.setStorage({
                key: 'openId',
                data: data.openid,
              });
              that.globalData.sessionKey = data.sessionKey
              that.check()
            }
          }
        }, {
          fail: function(res) {
          }
        }, {
          complete: function() {

          }
        })
      }
    })
  },
  check() {
    let that = this
    wx.getSetting({//查询授权信息
      success(res) {
        if (res.authSetting['scope.userInerInfo']) {//如果有过授权
          wx.getUserInfo({//获取信息进入解密
            success: function(res) {
              res.sessionKey = that.globalData.sessionKey
              that.getImportantData(res)
            }
          })
        } else {
          wx.redirectTo({
            url: '../authorization/authorization',
          })
        }
      }
    })
  },
  getImportantData(e) { // 未关注公众号 获取目的 unionid
    let that = this
    console.log(e)
    if (e.detail.encryptedData) {
      let data = {
        sessionKey: e.sessionKey,
        encryptedData: e.detail.encryptedData,
        rawData: e.detail.rawData,
        ivStr: e.detail.iv,
        signature: e.detail.signature,
      }
      promise.notAuthorizeRequest('miniapp/decryptUserInfo', 'POST', data, null, 4, 
       {
        success(res) {
          that.getIdentity(res.unionId)
          wx.setStorage({
            key: "unionId",
            data: res.unionId
          })
        }
        }, {
          fail: function (res) {

          }
        }, {
          complete: function () {

          }
        })
    }
  },
  getIdentity(unionId){//获取身份表
  let that=this
    promise.notAuthorizeRequest('account/getAccountSuitesByUnionId/' + unionId, 'GET', '', null, 4,
      {
        success(res) {
             for(let i=0;i<res.length;i++){
               that.globalData.accountSuite = res[0].accountSuite
             }
          promise.tLogin(unionId, that.globalData.accountSuite)
        }
      }, {
        fail: function (res) {

        }
      }, {
        complete: function () {

        }
      })
  },
  globalData:{
    sessionKey:'',
    accountSuite:''
  }
})